function registerSavings() {
	var parms = new Object();
	var url = "/index.php?mod=controller1";
	parms["action"] = "registerSavings";
	parms["budgetId"] = $("#budgetId").val();

	parms["expenseSavingsRowId"] = "";
	parms["expenseSavingsDescription"] = "";
	parms["expenseSavingsActual"] = "";
	$(".expenseSavingsRow").each(function() {
		parms["expenseSavingsActual"] += "," + $(this).find("input[name^='expensesSavingsActualAmt']").val();
		parms["expenseSavingsDescription"] += "," + $(this).find("[name^='expenseSavingsDescription']").html();
		parms["expenseSavingsRowId"] += "," + $(this).attr("id");
	});

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {

			$("#msgDlg").dialog( {
				bgiframe : true,
				autoOpen : false,
				title : "Saved successfully",
				modal : true,
				buttons : {
					Ok : function() {
						$(this).dialog('destroy');
					}
				}
			});

			$("#msgDlg").css('font-size', '0.8em');
			$("#msgDlg").html("Savings entered successfully.");
			$("#msgDlg").dialog("open");
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function deleteItem(link) {
	if ($(link).parent().parent().attr("id") == "") {
		$(link).parent().parent().remove();
		recalculcateAllTotals();
		return;
	}

	itemToDelete = link;

	$("#confirmDlg").dialog( {
		bgiframe : true,
		autoOpen : false,
		title : "Confirm?",
		modal : true,
		buttons : {
			"Cancel" : function() {
				$(this).dialog('destroy');
			},
			"Yes" : function() {
				doDeleteItem();
				$(this).dialog('destroy');
			}
		}
	});

	$("#confirmDlg").css('font-size', '0.8em');
	$("#confirmDlg").html("Are you sure you want to delete this row?");
	$("#confirmDlg").dialog("open");
}

function calculateTransactionTotal() {
	var total = 0;
	$(".itemAmount").each(function() {
		var amount = undoCurrencyFormatting($(this).html());
		total += amount;
	});
	$("#total").html("R " + formatCurrency(total.toFixed(2)));
}

function getPastDataForBudgetItem(budgetItemId, itemDescription) {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getPastDataForBudgetItem";
	parms["budgetItemId"] = budgetItemId;

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayPastDataGraph(resultData, itemDescription);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function displayPastDataGraph(data, itemDescription) {
	$("#chartdiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		autoOpen : false,
		resizable : false,
		title : "Expense Analysis",
		width : 700,
		height : 550,
		modal : true,
		buttons : {
			"Cancel" : function() {
				$("#chartdiv").html("");
				$(this).dialog('close');
			}
		}
	});

	$("#chartdiv").dialog("open");
	
	var numOfPoints = 0;
	$(data).find("BudgetStatViewBean").each(function(){
		numOfPoints++;
	});
	
	var count = 0;
	var budgetLine = "[";
	$(data).find("BudgetStatViewBean").each(function(){
		count++;
		budgetLine += "['" +$(this).find("month").text()+"',"+ $(this).find("budget").text()+"]"+ (count < numOfPoints ? "," : "]");
	});
	
	count = 0;
	var actualLine = "[";
	$(data).find("BudgetStatViewBean").each(function(){
		count++;
		actualLine += "['" +$(this).find("month").text()+"',"+ $(this).find("actual").text()+"]"+ (count < numOfPoints ? "," : "]");
	});
	
	actualLine = eval(actualLine);
	budgetLine = eval(budgetLine);
	plot9 = $.jqplot('chartdiv', [actualLine, budgetLine], {
	    	title:itemDescription +" Analysis",
	    	seriesDefaults: {
	            showMarker:false,
	            pointLabels: { show:false }
	          },
	    	legend:{show:true},
	     	axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer,
			tickOptions:{formatString:'%b %#d, %Y'}
	    		},
	    	yaxis:{min:0}},
		series:[
		        {label:'Actual', markerOptions:{style:'square'}}, 
		        {label:'Budget'}
		    ]
	});
}

function displayBudgetItemTransactions(data, itemDescription, budgetItemId) {
	$(".transRow").remove();

	$(data).find("Transaction").each(
			function() {
				var date = $(this).find("date").text();
				var description = $(this).find("description").text().replace("\\", "");
				var bankRef = shortenString($(this).find("bankRef").text().replace("\\", ""), 30);
				var amount = $(this).find("amount").text();
				var str = '<tr class="transRow"><td>' + date + '</td><td>' + description + '</td><td>'
						+ (bankRef == "" ? description : bankRef) + '</td><td class="itemAmount">R ' + formatCurrency(amount)
						+ '</td></tr>';
				$(str).insertAfter($("#budgetItemTransHeaderRow"));
			});
	calculateTransactionTotal();

	$("#budgetItemTransactionsDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 600,
		modal : true,
		resizable : false,
		title : itemDescription,
		buttons : {
			OK : function() {
				$(this).dialog("destroy");
			},
			"Edit Name" : function() {
				changeBudgetItemName(itemDescription, budgetItemId);
				$(this).dialog("destroy");
			},
			Analysis : function() {
				getPastDataForBudgetItem(budgetItemId, itemDescription);
				$(this).dialog("destroy");
			}
		}
	});
	$("#budgetItemTransactionsDiv").dialog("open");
}

function changeBudgetItemName(currentName, budgetItemId) {
	$("#changeBudgetItemDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 350,
		modal : true,
		resizable : false,
		title : 'Change "' + currentName + '"',
		buttons : {
			Submit : function() {
				doBudgetItemChange($("#currentBudgetItemName").val(), budgetItemId);
				$(this).dialog("destroy");
			},
			Cancel : function() {
				$(this).dialog("destroy");
			}
		}
	});

	$("#changeBudgetItemDiv").dialog("open");
	$("#currentBudgetItemName").val(currentName);
	$("#currentBudgetItemName").focus().select();
}

function doBudgetItemChange(newName, budgetItemId) {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "updateBudgetItem";
	parms["budgetItemId"] = budgetItemId;
	parms["description"] = newName;

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			alert("Budget item changed successfully.");
			location.reload();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function getBudgetItemTransactions(row) {

	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getBudgetItemTransactions";
	parms["budgetId"] = $("#budgetId").val();
	parms["budgetItemId"] = $(row).attr("id");
	parms["toDate"] = "endOfBudget";
	parms["fromDate"] = "startOfBudget";

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayBudgetItemTransactions(resultData, $(row).html(), parms["budgetItemId"]);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function doDeleteItem() {
	var parms = new Object();
	var url = "/index.php?mod=controller1";
	parms["action"] = "deleteBudgetItem";
	parms["budgetItemId"] = $(itemToDelete).parent().parent().attr("id");
	parms["budgetId"] = $("#budgetId").val();

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			$(itemToDelete).parent().parent().remove();
			recalculcateAllTotals();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function formatCurrency(n) {
	if (!isFinite(n)) {
		return n;
	}
	var s = "" + n, abs = Math.abs(n), _, i;
	if (abs >= 1000) {
		_ = ("" + abs).split(/\./);
		i = _[0].length % 3 || 3;

		_[0] = s.slice(0, i + (n < 0)) + _[0].slice(i).replace(/(\d{3})/g, ',$1');

		s = _.join('.');
	}
	return s;
}

function updateBudgetItemId(select, categoryId) {
	$(select).parent().parent().attr("id", $(select).val());
}

function displayCategoryBudgetItems(data, categoryId, descriptionVar) {
	var selectStr = "<select name='" + descriptionVar + "' onchange='updateBudgetItemId(this, " + categoryId + ");'>";
	var checkboxStr = "<input type='checkbox' id='existingItems' onchange='getExistingBudgetItems(" + categoryId
			+ ")' checked>Existing</input>";
	var count = 0;
	$(data).find("BudgetItem").each(function() {
		selectStr += "<option value='" + $(this).find("id").text() + "'>" + $(this).find("description").text() + "</option>";
		count++;
		if (count == 1) {
			$("input[name='" + descriptionVar + "']:last").parent().parent().attr("id", $(this).find("id").text());
		}
	});

	selectStr += "</select>";

	if (count == 0) {
		alert("Ther are no existing budget items that do not exist in this budget. Create a new one if you want.");
		$("#existingItems").attr("checked", false);
		return;
	}

	$("input[name='" + descriptionVar + "']:last").parent().html(selectStr + checkboxStr);

}

function getExistingBudgetItems(categoryId) {
	var catDesc = "";
	switch (categoryId) {
	case 1:
		catDesc = "incomeDescription";
		break;
	case 2:
		catDesc = "variableDescription";
		break;
	case 3:
		catDesc = "fixedDescription";
		break;
	case 4:
		catDesc = "expenseSavingsDescription";
		break;
	case 5:
		catDesc = "savingsDescription";
		break;
	default:
		catDesc = "incomeDescription";
	}

	if ($("#existingItems").attr("checked")) {
		var parms = new Object();
		var url = "/index.php?mod=controller1";
		parms["action"] = "getBudgetItemsForBudget";
		parms["categoryId"] = categoryId;
		parms["budgetId"] = $("#budgetId").val();

		$.post(url, parms, function(resultData) {
			if ($(resultData).find("code").text() == 0) {
				displayCategoryBudgetItems(resultData, categoryId, catDesc);
			} else {
				alert($(resultData).find("errMessage").text());
			}
		});
	} else {
		var checkboxStr = "<input type='checkbox' id='existingItems' onchange='getExistingBudgetItems(" + categoryId
				+ ")'>Existing</input>";
		$("select[name='" + catDesc + "']:last").parent().parent().attr("id", "");
		$("select[name='" + catDesc + "']:last").parent().html(
				"<input class='newInput textInput' name='" + catDesc + "' type='text'/>" + checkboxStr);
	}
}

var itemToDelete;

function createNewItem(catId) {
	var rowClass = "";
	var descriptionName = "";
	var budgetCol = "";
	var actualCol = "";
	var differenceCol = "";

	if (catId == 1) {
		rowClass = "incomeRow";
		descriptionName = "incomeDescription";
		budgetCol = "incomeBudget";
		actualCol = "incomeActual";
	} else if (catId == 2) {
		rowClass = "variableRow";
		descriptionName = "variableDescription";
		budgetCol = "variableBudgetAmt";
		actualCol = "variableActualAmt";
		differenceCol = "variableDifferenceAmt";
	} else if (catId == 3) {
		rowClass = "fixedRow";
		descriptionName = "fixedDescription";
		budgetCol = "fixedBudgetAmt";
		actualCol = "fixedActualAmt";
		differenceCol = "fixedDifferenceAmt";
	} else if (catId == 4) {
		rowClass = "expenseSavingsRow";
		descriptionName = "expenseSavingsDescription";
		budgetCol = "expensesSavingsBudgetAmt";
		actualCol = "expensesSavingsActualAmt";
		differenceCol = "expensesSavingsDifferenceAmt";
	} else if (catId == 5) {
		rowClass = "savingsRow";
		descriptionName = "savingsDescription";
		budgetCol = "savingsBudgetAmt";
		actualCol = "savingsActualAmt";
		differenceCol = "savingsDifferenceAmt";
	}

	var trString = '<tr class="'
			+ rowClass
			+ '"><th scope="row" class="spec"><input class="newInput textInput" name="'
			+ descriptionName
			+ '" type="text"/>'
			+ '<input type="checkbox" id="existingItems" onchange="getExistingBudgetItems('
			+ catId
			+ ');">Existing</input></</th>'
			+ '<td class="spec">R <input class="currency" name="'
			+ budgetCol
			+ '" type="text" onblur="recalculcateAllTotals();" value="0"></input></td>'
			+ '<td class="spec">R <input class="currency" name="'
			+ actualCol
			+ '" type="text" onblur="recalculcateAllTotals();" value="0"></input></td>'
			+ '<td class="spec">R <label name="'
			+ differenceCol
			+ '"></label></td><td>&nbsp;</td>'
			+ '<th class="spec">'
			+ '<a href="#" onclick="deleteItem(this);"><img src="images/delete.png" title="Delete this row" alt="Delete this row" border="0" width="10"/></a>'
			+ '</th></tr>';

	if (catId == 1) {
		if ($(".incomeHeader").next().attr("id") == "") {
			$(trString).insertAfter('.incomeHeader');
		} else if ($(".incomeHeader").next().attr("class") == null) {
			$(trString).insertAfter('.incomeHeader');
		} else {
			$(trString).insertAfter('.incomeRow:last');
		}
	} else if (catId == 2) {
		if ($(".variableHeader").next().attr("id") == "") {
			$(trString).insertAfter('.variableHeader');
		} else if ($(".variableHeader").next().attr("class") == null) {
			$(trString).insertAfter('.variableHeader');
		} else {
			$(trString).insertAfter('.variableRow:last');
		}
	} else if (catId == 3) {
		if ($(".fixedHeader").next().attr("id") == "") {
			$(trString).insertAfter('.fixedHeader');
		} else if ($(".fixedHeader").next().attr("class") == null) {
			$(trString).insertAfter('.fixedHeader');
		} else {
			$(trString).insertAfter('.fixedRow:last');
		}
	} else if (catId == 4) {
		if ($(".expenseSavingsHeader").next().attr("id") == "") {
			$(trString).insertAfter('.expenseSavingsHeader');
		} else if ($(".expenseSavingsHeader").next().attr("class") == null) {
			$(trString).insertAfter('.expenseSavingsHeader');
		} else {
			$(trString).insertAfter('.expenseSavingsRow:last');
		}
	} else if (catId == 5) {
		if ($(".savingHeader").next().attr("id") == "") {
			$(trString).insertAfter('.savingHeader');
		} else if ($(".savingHeader").next().attr("class") == null) {
			$(trString).insertAfter('.savingHeader');
		}  else {
			$(trString).insertAfter('.savingsRow:last');
		}
	}
}

function getUnreconciledTransactionsForBudget() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getUnreconciledTransactionsForBudget";
	parms["budgetId"] = $("#budgetId").val();
	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayUnreconciledTransactions(resultData);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function disableAutoRecon() {
	if ($("#autoReconcileCB").attr("checked")) {
		$("#transDescriptor").prop("disabled", false);
	} else {
		$("#transDescriptor").prop("disabled", true);
	}
}

function displayUnreconciledTransactions(data) {
	var count = 0;
	$(data).find("Transaction").each(function() {
		count++;
	});

	if (count > 0) {
		$("#reconcileTransactionsDiv").dialog( {
			bgiframe : true,
			autoOpen : false,
			width : 500,
			modal : false,
			title : "Selected Transaction",
			position : [ 'right', 'top' ],
			resizable : false,
			buttons : {
				Update : function() {
					insertBudgetItemIntoBudget();
				}
			}
		});

		$("#unreconciledTransactionsDiv").dialog( {
			bgiframe : true,
			autoOpen : false,
			width : 600,
			modal : true,
			title : "Unreconciled Transactions",
			position : [ 'left', 'top' ],
			resizable : false,
			buttons : {
				Close : function() {
					$("#transDate").datepicker("destroy");
					$("#unreconciledTransactionsDiv").dialog("destroy");
					$(this).dialog('close');
					$(this).dialog('destroy');
				}
			},
			close : function(event, ui) {
				$("#unreconciledTransactionsDiv").dialog("destroy");
				// alert("on close");
		}
		});

		$(data)
				.find("Transaction")
				.each(
						function() {
							var rowStr = '<tr class="transRow" id="'
									+ $(this).find("id").text()
									+ '" transactionType="'
									+ $(this).find("type").text()
									+ '"><th class="spec"><input type="radio" name="selectTrans" onclick="updateSelectedTransaction(this);"/></th>'
									+ '<th class="spec date">' + $(this).find("date").text() + '</th>'
									+ '<th class="spec bankRef">' + $(this).find("bankRef").text() + '</th>'
									+ '<th class="spec amount"> R' + $(this).find("amount").text() + '</th>' + '</tr>';
							$(rowStr).insertAfter($("#unreconciledRow"));
						});

		$("#unreconciledTransactionsDiv").dialog("open");

		$("#reconcileTransactionsDiv").dialog("open");

		populateCategories();
	}
}

function updateBudgetItemsForTranType(){
	$("#currentBudgetItemRow").find("select").each(function (){
		$(this).hide();
	});
	
	$("#"+$("#catSel").val()).show();
}

function populateCategories(select) {
	$(".catRow").remove();
	fetchCategories("budgetitem", select);
	fetchCategories("accounts", select);
}

function fetchCategories(type, select) {
	var action = "";
	if (type == "budgetitem") {
		action = "getAllBudgetItems";
	} else if (type == "accounts") {
		action = "getAccountsAsBudgetItems";
	}

	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = action;
	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			updateCategories(resultData, select);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function updateCategories(resultData, select) {
	$(resultData).find("BudgetItem").each(
			function() {
				var categoryId = $.trim($(this).find("categoryId").text());
				if (categoryId == "2") {
					$(
							"<option class='catRow' categoryId='"+categoryId+"' id='" + $.trim($(this).find("id").text()) + "' value='"
									+ $.trim($(this).find("id").text()) + "'>"
									+ $.trim($(this).find("description").text()) + "</option>").appendTo($("#budgetCategory"+categoryId));
				} else if (categoryId == "3") {
					$(
							"<option class='catRow' categoryId='"+categoryId+"' id='" + $.trim($(this).find("id").text()) + "' value='"
									+ $.trim($(this).find("id").text()) + "'>"
									+ $.trim($(this).find("description").text()) + "</option>").appendTo($("#budgetCategory"+categoryId));
				} else if (categoryId == "4") {
					$(
							"<option class='catRow' categoryId='"+categoryId+"' id='" + $.trim($(this).find("id").text()) + "' value='"
									+ $.trim($(this).find("id").text()) + "'>"
									+ $.trim($(this).find("description").text()) + "</option>").appendTo($("#budgetCategory"+categoryId));
				} else if (categoryId == "1") {
					$(
							"<option class='catRow' categoryId='"+categoryId+"' id='" + $.trim($(this).find("id").text()) + "' value='"
									+ $.trim($(this).find("id").text()) + "'>"
									+ $.trim($(this).find("description").text()) + "</option>").appendTo($("#budgetCategory"+categoryId));
				} else if (categoryId == "6") {
					// we need to remove the current account. we cant tranfer to
					// same account.
					if ($("#accountId").val() != categoryId) {
						$(
								"<option class='catRow' categoryId='"+categoryId+"' id='" + $.trim($(this).find("id").text()) + "' value='"
										+ $.trim($(this).find("id").text()) + "'>"
										+ $.trim($(this).find("description").text()) + "</option>").appendTo($("#budgetCategory"+categoryId));
					}
				}
			});
	$("input:radio[name='transactionType']:nth(0)").attr("checked", "checked");
	$("#catSel").val(select);
	$("#newBudgetItemRow").hide();
}

function updateSelectedTransaction(row) {
	$("#infoTable").fadeOut("normal", function() {
		$("#reconcileTransactionsTable").fadeIn("normal");
	});

	$("#dateField").html($(row).parent().parent().find(".date").html());
	$("#amountField").html($(row).parent().parent().find(".amount").html());
	$("#bankRefField").html($(row).parent().parent().find(".bankRef").html());
	$("#transDescriptor").val($(row).parent().parent().find(".bankRef").html());
	$("#reconcileTransactionsDiv").removeClass("currency");
	$("#transactionId").val($(row).parent().parent().attr("id"));
	$("#transactionType").val($(row).parent().parent().attr("transactionType"));
	$("#transDescription").val("");
	$("#autoReconcileCB").removeAttr("checked");
	$('#currentBudgetItemRow').show();
}

function updateDescription(select) {
	if ($("#transDescription").val() == "") {
		$("#transDescription").val($.trim($(select).find("option:selected").text()));
	}
}

function insertBudgetItemIntoBudget() {
	var url = "/index.php?mod=controller1";	
	var parms = new Object();
	parms["action"] = "insertBudgetItemIntoBudget";
	parms["budgetId"] = $("#budgetId").val();
	
	//if new budgetItem, create it
	if($("#newBudgetItemRow").is(":visible") && !!($("#newBudgetItem").val()))
	{
		parms["budgetId"] = createBudgetItem();
	}
	parms["budgetItemId"] = $("#catSel").find("option:selected").val();
	parms["budgetAmount"] = 0;
	parms["actualAmount"] = 0;

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			saveTransaction();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function saveTransaction() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "saveTransaction";
	parms["transId"] = $("#transactionId").val();
	parms["accId"] = "";
	parms["transDate"] = $("#dateField").html();
	parms["transDescription"] = $("#transDescription").val();
	parms["autoReconcile"] = $("#autoReconcileCB").attr("checked");
	parms["transDescriptor"] = $("#transDescriptor").val();
	parms["categoryId"] = $("#catSel").find("option:selected").attr("categoryId");
	parms["budgetItemId"] = $("#catSel").find("option:selected").val();
	parms["reconciled"] = 1;
	var amount = $("#amountField").html().replace("R", "");

	parms["transAmount"] = $("#transactionType").val() == "expense" ? eval(amount) * -1 : amount;
	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {

			if (parms["autoReconcile"])
				processAutoReconTransaction(parms["autoReconcile"], parms["transDescriptor"]);
			else
				processNoneAutoTransaction();

		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function processAutoReconTransaction(autoreconcileFlag, autoreconcileKey) {
	var selectedRow = $(".transRow").find("input[type='radio']:checked").parent().parent();
	$(selectedRow).remove();

	if (autoreconcileFlag) {
		$(".transRow").each(function() {
			var nextSelected = $(this).find(".bankRef");
			if (nextSelected.html().indexOf(autoreconcileKey) != -1) {
				$("#transactionId").val($(this).attr("id"));
				$("#autoReconcileCB").removeAttr("checked");
				$("#amountField").html($(this).find(".amount").html());
				$("#transactionType").val($(this).attr("transactionType"));
				$("#transDescriptor").val(autoreconcileKey);
				saveTransaction();

				$(this).remove();
			}
		});
	}

	// select first transRow
	$(".transRow").each(function() {
		var nextSelected = $(this).find("input[type='radio']");
		nextSelected.attr("checked", "checked");
		updateSelectedTransaction(nextSelected);
	});
}

function processNoneAutoTransaction() {
	var selectedRow = $(".transRow").find("input[type='radio']:checked").parent().parent();
	$(selectedRow).remove();

	// select first transRow
	$(".transRow").each(function() {
		var nextSelected = $(this).find("input[type='radio']");
		nextSelected.attr("checked", "checked");
		updateSelectedTransaction(nextSelected);
	});
}

function createBudgetItem() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "createBudgetItem";
	parms["categoryId"] = $("#catSel").find("option:selected").val().replace("budgetCategory","");
	parms["description"] = $("#newBudgetItem").val();

	if ((parms["description"] == "") || (parms["categoryId"] == 0)) {
		alert("You need to fill in the budget item name and select a category.");
		return;
	}

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			var budgetItemId = $(resultData).find("budgetItemId").text();
			populateCategories(budgetItemId);
			return budgetItemId;
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

$(document).ready(function() {
	
	//We hide the Savings & Cheque accounts recon info if the accounts are in sync
	if ($("#savingsRecon").attr("diffVal") == "0"){
		$("#savingsRecon").hide();
	}
	
	$.jqplot.config.enablePlugins = true;

	$("#calcBtn").button();
	$("#saveButton").button();
	$("#cancelButton").button();

	getUnreconciledTransactionsForBudget();

	$("input").blur(function() {
		recalculcateAllTotals();
	});

	$("input").attr("class", "currency");

	$("#cancelButton").click(function() {
		top.location = "/index.php?mod=viewBudgets";
	});

	$("#saveButton").click(function() {
		var parms = new Object();
		var url = "/index.php?mod=saveBudget";
		parms["budgetId"] = $("#budgetId").val();

		/* CARRY OVER */
		parms["carryOver"] = $("#carryOver").val();

		/* INCOME */
		parms["incomeRowId"] = "";
		parms["incomeBudget"] = "";
		parms["incomeActual"] = "";
		parms["incomeDescription"] = "";
		$(".incomeRow").each(function() {
			if ($(this).attr("id") == "") {
				parms["incomeRowId"] += ",0";
				parms["incomeDescription"] += "," + $(this).find("a").val();
			} else {
				parms["incomeRowId"] += "," + $(this).attr("id");
				parms["incomeDescription"] += "," + $(this).find("a").html();
			}

			
			parms["incomeBudget"] += "," + $(this).find("input[name^='incomeBudget']").val();
			parms["incomeActual"] += "," + $(this).find("input[name^='incomeActual']").val();
		});

		/* Monthly Variable Expenses */
		parms["variableRowId"] = "";
		parms["variableBudget"] = "";
		parms["variableActual"] = "";
		parms["variableDescription"] = "";
		$(".variableRow").each(function() {
			if ($(this).attr("id") == null) {
				parms["variableRowId"] += ",0";
				parms["variableDescription"] += "," + $(this).find(".newInput").val();
			} else {
				parms["variableRowId"] += "," + $(this).attr("id");
				parms["variableDescription"] += "," + $(this).find("a").html();
			}

			parms["variableBudget"] += "," + $(this).find("input[name^='variableBudgetAmt']").val();
			parms["variableActual"] += "," + $(this).find("input[name^='variableActualAmt']").val();
		});

		/* Monthly Fixed Expenses */
		parms["fixedRowId"] = "";
		parms["fixedBudget"] = "";
		parms["fixedActual"] = "";
		parms["fixedDescription"] = "";
		$(".fixedRow").each(function() {
			if ($(this).attr("id") == null) {
				parms["fixedRowId"] += ",0";
				parms["fixedDescription"] += "," + $(this).find(".newInput").val();
			} else {
				parms["fixedRowId"] += "," + $(this).attr("id");
				parms["fixedDescription"] += "," + $(this).find("a").html();
			}

			parms["fixedBudget"] += "," + $(this).find("input[name^='fixedBudgetAmt']").val();
			parms["fixedActual"] += "," + $(this).find("input[name^='fixedActualAmt']").val();
		});

		/* Monthly Expenses Savings */
		parms["expenseSavingsRowId"] = "";
		parms["expenseSavingsBudget"] = "";
		parms["expenseSavingsActual"] = "";
		parms["expenseSavingsDescription"] = "";
		$(".expenseSavingsRow").each(function() {
			if ($(this).attr("id") == null) {
				parms["expenseSavingsRowId"] += ",0";
				parms["expenseSavingsDescription"] += "," + $(this).find(".newInput").val();
			} else {
				parms["expenseSavingsRowId"] += "," + $(this).attr("id");
				parms["expenseSavingsDescription"] += "," + $(this).find("a").html();
			}

			parms["expenseSavingsBudget"] += "," + $(this).find("input[name^='expensesSavingsBudgetAmt']").val();
			parms["expenseSavingsActual"] += "," + $(this).find("input[name^='expensesSavingsActualAmt']").val();
		});

		/* Monthly Savings */
		parms["savingsRowId"] = "";
		parms["savingsBudget"] = "";
		parms["savingsActual"] = "";
		parms["savingsDescription"] = "";
		$(".savingsRow").each(function() {
			if ($(this).attr("id") == null) {
				parms["savingsRowId"] += ",0";
				parms["savingsDescription"] += "," + $(this).find(".newInput").val();
			} else {
				parms["savingsRowId"] += "," + $(this).attr("id");
			}
			parms["savingsDescription"] += "," + $(this).find("a").html();
			parms["savingsBudget"] += "," + $(this).find("input[name^='savingsBudgetAmt']").val();
			parms["savingsActual"] += "," + $(this).find("input[name^='savingsActualAmt']").val();
		});

		$.post(url, parms, function(resultData) {
			if ($("code", resultData).html() == 0) {
				$(".newInput").each(function() {
					var input = $(this);
					$(input).parent().attr("name", $(input).attr("name"));
					$(input).parent().html($(input).val());
				});
				top.location = "index.php?mod=editBudget&budgetId=" + $("#budgetId").val();

			} else {
				alert("broken");
			}
		});
	});

	recalculcateAllTotals();
	doExpenseColorCoding();
});

function doExpenseColorCoding() {
	$(".variableStatus").each(
			function() {
				var str = '<table width="90%" height="5" cellpadding="0" cellspacing="0"><tr><td class="vshade">' + $(this)
						.html() + '</td></tr></table>';
				$(this).html(str);
			});

	$(".vshade").each(function() {
		var percentage = $(this).html();
		$(this).html("");
		$(this).css("backgroundColor", getColorCodeForVariableExpenses(percentage));
		$(this).parent().parent().append("<span style='font-size: 0.5em'>" + percentage + "%</span>");
	});

	$(".fixedStatus").each(
			function() {
				var str = '<table width="90%" height="5" cellpadding="0" cellspacing="0"><tr><td class="fshade">' + $(this)
						.html() + '</td></tr></table>';
				$(this).html(str);
			});

	$(".fshade").each(function() {
		var percentage = $(this).html();
		$(this).html("");
		$(this).css("backgroundColor", getColorCodeForFixedExpenses(percentage));
		$(this).parent().parent().append("<span style='font-size: 0.5em'>" + (percentage==-1 ? "" : (percentage+"%")) + "</span>");
	});
	
	//set budget items to those of selected tran type
	updateBudgetItemsForTranType();
}

function getVal(value) {
	if (value == "")
		return 0;
	else
		return value;
}

var budgetIncomeTotal;
var actualIncomeTotal;

var variableBudgetTotal;
var variableActualTotal;
var variableDifferenceTotal;

var fixedBudgetTotal;
var fixedActualTotal;
var fixedDifferenceTotal;

var expensesSavingsBudgetTotal;
var expensesSavingsActualTotal;
var expensesSavingsDifferenceTotal;

var savingsBudgetTotal;
var savingsActualTotal;
var savingsDifferenceTotal;

function recalculateIncomeTotals() {
	var total = eval($("#carryOver").val());
	$('input[name^="incomeBudget"]').each(function() {
		total = total + eval(getVal($(this).val()));
	});
	$("#budgetIncomeTotal").html("R " + formatCurrency(total));
	budgetIncomeTotal = total;

	total = eval($("#carryOver").val());

	$('input[name^="incomeActual"]').each(function() {
		total = total + eval(getVal($(this).val()));

		// We insert 0's if the field is empty
			if ($(this).val() == "") {
				$(this).val(0);
			}
		});
	$("#actualIncomeTotal").html("R " + formatCurrency(total.toFixed(2)));
	actualIncomeTotal = total;

}

function recalculateVariableTotals() {
	var budgetTotal = 0;
	var actualTotal = 0;

	// BUDGET
	$('input[name^="variableBudgetAmt"]').each(function() {
		budgetTotal = budgetTotal + eval(getVal($(this).val()));
		var bud = getVal($(this).val());
		var act = $(this).parent().parent().find('input[name^="variableActualAmt"]').val();
		var rowDifference = bud - act;

		$(this).parent().parent().find('label[name^="variableDifferenceAmt"]').html(rowDifference.toFixed(2));

	});
	$("#variableBudgetTotal").html("R " + formatCurrency(budgetTotal));

	// ACTUAL
	$('input[name^="variableActualAmt"]').each(function() {
		actualTotal = actualTotal + eval(getVal($(this).val()));
	});
	$("#variableActualTotal").html("R " + formatCurrency(actualTotal.toFixed(2)));

	$("#variableDifferenceTotal").html("R " + formatCurrency((budgetTotal - actualTotal).toFixed(2)));

	// Update global variables
	variableBudgetTotal = budgetTotal;
	variableActualTotal = actualTotal;
	variableDifferenceTotal = (budgetTotal - actualTotal).toFixed(2);
}

function recalculateFixedTotals() {
	var budgetTotal = 0;
	var actualTotal = 0;

	// BUDGET
	$('input[name^="fixedBudgetAmt"]').each(function() {
		budgetTotal = budgetTotal + eval(getVal($(this).val()));
		var bud = getVal($(this).val());
		var act = $(this).parent().parent().find('input[name^="fixedActualAmt"]').val();
		var rowDifference = bud - act;

		$(this).parent().parent().find('label[name^="fixedDifferenceAmt"]').html(rowDifference.toFixed(2));

	});
	$("#fixedBudgetTotal").html("R " + formatCurrency(budgetTotal.toFixed(2)));

	// ACTUAL
	$('input[name^="fixedActualAmt"]').each(function() {
		actualTotal = actualTotal + eval(getVal($(this).val()));
	});
	$("#fixedActualTotal").html("R " + formatCurrency(actualTotal.toFixed(2)));

	$("#fixedDifferenceTotal").html("R " + formatCurrency((budgetTotal - actualTotal).toFixed(2)));

	// Update gloval variables;
	fixedBudgetTotal = budgetTotal;
	fixedActualTotal = actualTotal;
	fixedDifferenceTotal = (budgetTotal - actualTotal).toFixed(2);
}

function recalculateExpenseSavingsTotals() {
	var budgetTotal = 0;
	var actualTotal = 0;

	// BUDGET
	$('input[name^="expensesSavingsBudgetAmt"]').each(function() {
		budgetTotal = budgetTotal + eval(getVal($(this).val()));
		var bud = getVal($(this).val());
		var act = $(this).parent().parent().find('input[name^="expensesSavingsActualAmt"]').val();
		var rowDifference = bud - act;

		$(this).parent().parent().find('label[name^="expensesSavingsDifferenceAmt"]').html(rowDifference.toFixed(2));

	});
	$("#expensesSavingsBudgetTotal").html("R " + formatCurrency(budgetTotal));

	// ACTUAL
	$('input[name^="expensesSavingsActualAmt"]').each(function() {
		actualTotal = actualTotal + eval(getVal($(this).val()));
	});
	$("#expensesSavingsActualTotal").html("R " + formatCurrency(actualTotal));

	$("#expensesSavingsDifferenceTotal").html("R " + formatCurrency((budgetTotal - actualTotal).toFixed(2)));

	// Update global variables
	expensesSavingsBudgetTotal = budgetTotal;
	expensesSavingsActualTotal = actualTotal;
	expensesSavingsDifferenceTotal = (budgetTotal - actualTotal).toFixed(2);
}

function recalculateSavingsTotals() {
	var budgetTotal = 0;
	var actualTotal = 0;

	// BUDGET
	$('input[name^="savingsBudgetAmt"]').each(function() {
		budgetTotal = budgetTotal + eval(getVal($(this).val()));
		var bud = getVal($(this).val());
		var act = $(this).parent().parent().find('input[name^="savingsActualAmt"]').val();
		var rowDifference = bud - act;

		$(this).parent().parent().find('label[name^="savingsDifferenceAmt"]').html(rowDifference.toFixed(2));

	});
	$("#savingsBudgetTotal").html("R " + formatCurrency(budgetTotal));

	// ACTUAL
	$('input[name^="savingsActualAmt"]').each(function() {
		actualTotal = actualTotal + eval(getVal($(this).val()));
	});
	$("#savingsActualTotal").html("R " + formatCurrency(actualTotal));

	$("#savingsDifferenceTotal").html("R " + formatCurrency((budgetTotal - actualTotal).toFixed(2)));

	// Update global variables
	savingsBudgetTotal = budgetTotal;
	savingsActualTotal = actualTotal;
	savingsDifferenceTotal = (budgetTotal - actualTotal).toFixed(2);
}

function recalculateMainTotal() {
	var totalBudgetedBudget = (variableBudgetTotal + fixedBudgetTotal + expensesSavingsBudgetTotal + savingsBudgetTotal);
	var totalActualBudget = (variableActualTotal + fixedActualTotal + expensesSavingsActualTotal + savingsActualTotal);
	$("#totalBudgetedBudget").html("R " + formatCurrency(totalBudgetedBudget.toFixed(2)));
	$("#totalActualBudget").html("R " + formatCurrency(totalActualBudget.toFixed(2)));
	$("#totalDifferenceBudget").html("R " + formatCurrency((totalBudgetedBudget - totalActualBudget).toFixed(2)));

	$("#totalBudgetSurplus").html("R " + formatCurrency((budgetIncomeTotal - totalBudgetedBudget).toFixed(2)));
	// $("#totalActualSurplus").html("R "+ (actualIncomeTotal -
	// totalActualBudget).toFixed(2));
	$("#totalRemainingSurplus").html("R " + formatCurrency((actualIncomeTotal - totalActualBudget).toFixed(2)));
}

function recalculcateAllTotals() {
	recalculateIncomeTotals();
	recalculateVariableTotals();
	recalculateFixedTotals();
	recalculateExpenseSavingsTotals();
	recalculateSavingsTotals();
	recalculateMainTotal();
}
